package com.crazy.bookstore.controller.admin;

import com.crazy.bookstore.common.ApiRestResponse;
import com.crazy.bookstore.entity.Member;
import com.crazy.bookstore.exception.ExceptionEnum;
import com.crazy.bookstore.exception.MyException;
import com.crazy.bookstore.service.MemberService;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * @author: 卢辉宇
 * @date: 2023/1/2 19:21
 * @description:
 */
@RestController
public class LoginForAdminController {

    @Resource
    MemberService memberService;

    /**
     * 管理员登录
     * @param username
     * @param password
     * @param vc
     * @param request
     * @return
     * @throws MyException
     */
    @PostMapping("/loginforadmin")
    public ApiRestResponse login(String username, String password, String vc, HttpServletRequest request) throws MyException {
        //从会话中拿到当前存储的验证码
        String verifyCode = (String)request.getSession().getAttribute("kaptchaVerifyCode");
        if(vc==null||!vc.equalsIgnoreCase(verifyCode)){
            /*验证码错误*/
            throw new MyException(ExceptionEnum.VERIFY_CODE_ERROR);
        }

        Member member = memberService.checkLogin(username, password);
        if (member.getAdmin()!=1){
            //不是管理员
            throw new MyException(ExceptionEnum.NEED_ADMIN);
        }

        member.setPassword(null);
        member.setSalt(null);
        //保存到session中
        request.getSession().setAttribute("member",member);

        return ApiRestResponse.seccess(member);
    }

}
